package cluster

import akka.actor.typed.Behavior
import akka.actor.typed.receptionist.{Receptionist, ServiceKey}
import akka.actor.typed.scaladsl.Behaviors
import test.ChildActor
import tool.Pojo._

/**
 * Created by yz on 30/9/2020
 */
object MyDb {

  val myDbKey = ServiceKey[ChildCommand]("childService")

  def apply(): Behavior[ChildCommand] = {

    Behaviors.setup[ChildCommand] { context =>
      context.system.receptionist ! Receptionist.register(myDbKey, context.self)
      boot(Map.empty)
    }
  }

  def boot(map: Map[String, Object]): Behavior[ChildCommand] = Behaviors.receive[ChildCommand] { (context, message) =>
    val log = context.log
    message match {
      case SetRequest(key, value, mainRef) =>
        context.log.info("come in")
        log.info("received SetRequest - key: {} value: {}", key, value)
        val newMap = map.updated(key, value)
        boot(newMap)
      case GetRequest(key, mainRef) =>
        log.info("received GetRequest - key: {}", key)
        val response = map.get(key)
        mainRef ! Value(response)
        Behaviors.same
    }
  }

}

